package com.grad.webstudy.exceptions;

import com.aliyuncs.exceptions.ClientException;
import com.grad.webstudy.common.Result;
import com.grad.webstudy.enums.ExceptionEnums;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

import javax.validation.ConstraintViolationException;

/**
 * @Description: 统一全局异常处理
 * @Author: zjf
 * @Date: 2020/1/14 17:29.
 */

@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    public Result handle(Exception e) {
        Result result = new Result();

        if (e instanceof UserException) {
            result.setMsg("操作失败：" + e.getMessage());
            result.setData(e.getMessage());
        } else if (e instanceof ConstraintViolationException) {
            result.setCode(ExceptionEnums.PARAM_ERROR.getCode());
            result.setMsg("操作失败：" + e.getMessage());
            result.setData(false);
        } else if (e instanceof CodeException) {
            result.setCode(ExceptionEnums.VALID_CODE_ERROR.getCode());
            result.setMsg("操作失败：" + e.getMessage());
            result.setData(false);
        } else if (e instanceof MissingServletRequestParameterException) {
            result.setCode(ExceptionEnums.PARAM_LOSS_ERROR.getCode());
            result.setMsg("操作失败: 参数 '" +((MissingServletRequestParameterException) e).getParameterName()+"' 缺失" );
            result.setData(false);
        } else if (e instanceof AliyunException) {
            result.setCode(ExceptionEnums.ALIYUN_ERROR.getCode());
            result.setMsg("操作失败" + e.getMessage());
            result.setData(false);
        } else if (e instanceof CustomException) {
            result.setCode(((CustomException) e).getCode());
            result.setMsg("操作失败" + e.getMessage());
            result.setData(false);
        } else if (e instanceof MultipartException) {
            result.setMsg("操作失败" + e.getMessage());
            result.setData(false);
        } else {
            result.setCode(ExceptionEnums.INTERNAL_ERROR.getCode());
            result.setMsg("操作失败" + ExceptionEnums.INTERNAL_ERROR.getMessage());
            result.setData(false);
        }
        return result;
    }
}
